#pragma once
#include "logMessage.hpp"
#include "Protocal.hpp"

#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <strings.h>
#include <functional>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <signal.h>
using namespace std;

namespace Server
{
    typedef function<bool(const Request &, Response &)> func_t;
    enum
    {
        SOCKET_ERR = 1,
        BIND_ERR,
        LISTEN_ERR,
        ACCEPT_ERR,
        USAGE_ERR,
    };

    static const uint16_t gPort = 8080;
    static const int gbacklog = 5;

    void HandlerEntery(int sock, func_t func)
    {
        string inbuffer;
        while (1)
        {
            string package,text_str;
            // 1.获取一个有效的报文  "content_len"\r\n"x + y"\r\n
            if(!recvPackage(sock,inbuffer,&package))
            {
                return;
            }
            cout << "带有报头协议的报文为: " << package << endl;
            // 1.1 进行去掉报头协议
            if(!deLength(package,&text_str))
            {
                return;
            }
            cout << "success! 去掉协议报头的报文为: " << text_str << endl; // "x + y"
            // 2.进行反序列化
            Request req;
            if(!req.deSerialize(text_str))
            {
                return;  //此时就得到了一个结构化对象 里面进行了解析填充
            }
            cout << "客户端发送的数据反序列化成功!" << endl;
            // 3.调用func函数进行计算操作  构造成Response回应进行发送
            // logMessage(NORMAL, "反序列化 success!");
            Response res;
            func(req, res);//此时上层处理的结果就填充到了res里面
            //logMessage(NORMAL, "上层计算完成!");

            //3.1将res结构化对象序列化成字符串
            string resp_str;
            res.Serialize(&resp_str);
            cout << "计算已经完成，且完成了序列化，结果为: " << resp_str << endl;
            // 4.添加协议报头，将结果返回给客户端
            string send_resp_str = enLength(resp_str);
            cout << "添加协议报头完整的响应为: " << send_resp_str << endl;

            send(sock, send_resp_str.c_str(), send_resp_str.size(), 0);
        }
    }

    class CalServer
    {
    public:
        CalServer(const uint16_t &port = gPort)
            : _listensock(-1), _port(port)
        {
        }
        ~CalServer()
        {
        }

        void InitCalServer()
        {
            // 1.创建套接字 面向字节流
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                logMessage(FATAL, "Create Socket Fail!");
                exit(SOCKET_ERR);
            }
            logMessage(NORMAL, "Create Socket Success!");

            // 2.bind
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            peer.sin_addr.s_addr = INADDR_ANY; // IP地址绑定任意的
            peer.sin_family = AF_INET;
            peer.sin_port = htons(_port);

            if (bind(_listensock, (struct sockaddr *)&peer, sizeof(peer)) < 0)
            {
                logMessage(FATAL, "Bind Socket Fail!");
                exit(BIND_ERR);
            }
            logMessage(NORMAL, "Bind Socket Success!");

            // 3.Socket 设置为监听状态
            if (listen(_listensock, gbacklog) < 0)
            {
                // 设置失败
                logMessage(FATAL, "Listen Socket Fail!");
                exit(LISTEN_ERR);
            }
            logMessage(NORMAL, "Listen Socket Success!");
        }
        void Start(func_t func)
        {
            //signal(SIGCHLD, SIG_IGN); // 忽略掉子进程发送信号的方式

            while (1)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                int sock = accept(_listensock, (struct sockaddr *)&peer, &len);
                if (sock < 0)
                {
                    logMessage(FATAL, "Accept Socket Fail!");
                    //exit(ACCEPT_ERR);
                    continue;//继续去接受新的链接
                }
                logMessage(NORMAL, "Accpet Socket Success!");
                cout << "new sock# " << sock << endl;
                // 多进程版  version 2
                // 交给子进程进行处理
                pid_t pid = fork();
                if (pid == 0) // child
                {
                    // 子进程会继承父进程的fd  close不需要的
                    close(_listensock);
                    // version 2 采用孙子进程的方式去完成调用
                    if(fork() > 0)
                    {
                        exit(0);
                    }

                    HandlerEntery(sock, func);
                    close(sock);
                    exit(0); // 孤儿进程
                }
                // parent  回收子进程
                close(sock);
                //在这里去wait爸爸进程  否则造成僵尸进程
                pid_t n = waitpid(pid, nullptr, 0);
                if(n > 0)
                {
                    cout << "wait 父亲进程 success!" << endl;
                }
            }
        }

    private:
        int _listensock;
        uint16_t _port;
    };
}